package com.example.netty.nio.chatDemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

/**
 * NIO 群聊 demo 客户端1
 *
 * @author LSQ
 * @since 2023/2/18 14:19
 */
public class ChatClient2 {

    private final String HOST = "127.0.0.1";
    private final int PORT = 8888;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    /**
     * 客户端初始化
     *
     * @author LSQ
     * @since 2023/2/18 14:36
     */
    public ChatClient2() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务端发送数据
     *
     * @param info 数据
     * @author LSQ
     * @since 2023/2/18 14:41
     */
    public void sendInfo(String info) {
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 从服务端读取数据
     *
     * @author LSQ
     * @since 2023/2/18 14:41
     */
    public void readInfo() {
        try {
            while (selector.select() > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len;
                    while ((len = socketChannel.read(byteBuffer)) > 0) {
                        System.out.println("服务端传来的消息：" + new String(byteBuffer.array(), StandardCharsets.UTF_8));
                    }
                    it.remove();
                }
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChatClient2 chatClient = new ChatClient2();

        // 启动一个线程 用来接收服务端传来的数据
        new Thread(() -> {
            chatClient.readInfo();
        }).start();

        // 向服务端发送数据
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            chatClient.sendInfo(scanner.nextLine());
        }
    }

}
